<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true">
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/pages/accounting/index" class="back-navigator">
					<view class="back-content">
						<u-icon color="#1e88e5" name="arrow-left"></u-icon>
						<text class="navbar-title">编辑记录</text>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<!-- 主内容区 -->
		<view class="content-container">
			<view class="form-card">
				<form class="record-form" @submit.prevent="saveRecord">

					<!-- 记录信息 -->
					<view class="form-section">
						<view class="form-row">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">记录类型</text>
									<text class="required-star">*</text>
								</view>
								<picker class="picker-field" mode="selector" :range="recordTypes" range-key="label"
									v-model="selectedRecordType" @change="onRecordTypeChange">
									<view class="picker-display">
										{{ selectedRecordType === -1 ? '请选择记录类型' : recordTypes[selectedRecordType].label }}
									</view>
								</picker>
							</view>
						</view>

						<!-- 收入分类 -->
						<view class="form-row" v-if="selectedRecordType === 0">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">收入类型</text>
									<text class="required-star">*</text>
								</view>
								<picker class="picker-field" mode="selector" :range="incomeCategories" range-key="label"
									v-model="selectedCategory" @change="onCategoryChange">
									<view class="picker-display">
										{{ selectedCategory === -1 ? '请选择收入类型' : incomeCategories[selectedCategory].label }}
									</view>
								</picker>
							</view>
						</view>

						<!-- 支出分类 -->
						<view class="form-row" v-if="selectedRecordType === 1">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">支出类型</text>
									<text class="required-star">*</text>
								</view>
								<picker class="picker-field" mode="selector" :range="expenseCategories"
									range-key="label" v-model="selectedCategory" @change="onCategoryChange">
									<view class="picker-display">
										{{ selectedCategory === -1 ? '请选择支出类型' : expenseCategories[selectedCategory].label }}
									</view>
								</picker>
							</view>
						</view>

						<view class="form-row">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">金额¥</text>
									<text class="required-star">*</text>
								</view>
								<view class="input-wrapper">
									<input type="number" placeholder="请输入金额" class="text-input" v-model="amount"
										@input="validateAmount" required>
								</view>
							</view>
						</view>

						<view class="form-row">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">日期</text>
									<text class="required-star">*</text>
								</view>
								<picker mode="date" class="date-picker" start="2010-01-01" end="2099-12-31"
									:value="selectedDate" @change="onDateChange">
									<view class="picker-display">
										{{ selectedDate || '请选择日期' }}
									</view>
								</picker>
							</view>
						</view>

						<view class="form-row">
							<view class="form-field">
								<view class="label-container">
									<text class="field-label">备注</text>
								</view>
								<textarea class="textarea-field" placeholder="请输入备注信息" v-model="remarks"
									rows="3"></textarea>
							</view>
						</view>
					</view>
				</form>
			</view>
		</view>

		<!-- 底部固定按钮区域 -->
		<view class="fixed-bottom-buttons">
			<navigator url="/pageNew/pages/accounting/index" class="btn cancel-btn" @click.stop>
				取消
			</navigator>
			<button class="btn save-btn" @click="saveRecord">
				保存
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 记录ID
				recordId: '',

				// 记录类型
				recordTypes: [{
						value: 'income',
						label: '收入'
					},
					{
						value: 'expense',
						label: '支出'
					}
				],
				selectedRecordType: -1,

				// 收入分类
				incomeCategories: [{
						value: 'salary',
						label: '工资收入'
					},
					{
						value: 'business',
						label: '经营收入'
					},
					{
						value: 'investment',
						label: '投资收益'
					},
					{
						value: 'other',
						label: '其他收入'
					}
				],

				// 支出分类
				expenseCategories: [{
						value: 'food',
						label: '餐饮'
					},
					{
						value: 'transportation',
						label: '交通'
					},
					{
						value: 'housing',
						label: '住房'
					},
					{
						value: 'entertainment',
						label: '娱乐'
					},
					{
						value: 'education',
						label: '教育'
					},
					{
						value: 'medical',
						label: '医疗'
					},
					{
						value: 'business',
						label: '商务'
					},
					{
						value: 'other',
						label: '其他'
					}
				],

				// 选中的分类
				selectedCategory: -1,

				// 金额
				amount: '',

				// 日期
				selectedDate: '',

				// 备注
				remarks: ''
			};
		},
		onLoad(options) {
			if (options && options.id) {
				this.recordId = options.id;
				this.loadRecord();
			} else {
				// 处理没有ID的情况
				this.selectedDate = this.formatDate(new Date());
			}
		},
		methods: {
			loadRecord() {
				try {
					let accountingRecords = uni.getStorageSync('accountingRecords') || [];
					// 确保是数组
					if (!Array.isArray(accountingRecords)) {
						accountingRecords = [];
					}
					const foundRecord = accountingRecords.find(record => record.id === this.recordId);

					if (foundRecord) {
						this.selectedRecordType = this.recordTypes.findIndex(type => type.value === foundRecord.type);

						if (foundRecord.type === 'income') {
							this.selectedCategory = this.incomeCategories.findIndex(
								category => category.value === foundRecord.category
							);
						} else {
							this.selectedCategory = this.expenseCategories.findIndex(
								category => category.value === foundRecord.category
							);
						}

						this.amount = foundRecord.amount ? foundRecord.amount.toString() : '';
						this.selectedDate = foundRecord.date || this.formatDate(new Date());
						this.remarks = foundRecord.remarks || '';
					} else {
						this.selectedDate = this.formatDate(new Date());
					}
				} catch (e) {
					console.error('加载记录失败:', e);
					this.selectedDate = this.formatDate(new Date());
				}
			},

			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			onRecordTypeChange(e) {
				this.selectedRecordType = e.detail.value;
				this.selectedCategory = -1;
			},

			onCategoryChange(e) {
				this.selectedCategory = e.detail.value;
			},

			onDateChange(e) {
				this.selectedDate = e.detail.value;
			},

			validateAmount() {
				if (this.amount && parseFloat(this.amount) < 0) {
					this.amount = '';
					uni.showToast({
						title: '金额不能为负数',
						icon: 'none'
					});
				}
			},

			saveRecord() {
				// 表单验证
				if (this.selectedRecordType === -1) {
					uni.showToast({
						title: '请选择记录类型',
						icon: 'none'
					});
					return;
				}

				if (this.selectedCategory === -1) {
					uni.showToast({
						title: `请选择${this.recordTypes[this.selectedRecordType].label}类型`,
						icon: 'none'
					});
					return;
				}

				if (!this.amount || parseFloat(this.amount) <= 0) {
					uni.showToast({
						title: '请输入有效的金额',
						icon: 'none'
					});
					return;
				}

				if (!this.selectedDate) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					});
					return;
				}

				try {
					let accountingRecords = uni.getStorageSync('accountingRecords') || [];
					if (!Array.isArray(accountingRecords)) {
						accountingRecords = [];
					}
					const index = accountingRecords.findIndex(record => record.id === this.recordId);

					if (index !== -1) {
						const recordType = this.recordTypes[this.selectedRecordType].value;
						accountingRecords[index] = {
							...accountingRecords[index],
							type: recordType,
							category: recordType === 'income' ?
								this.incomeCategories[this.selectedCategory].value : this.expenseCategories[this
									.selectedCategory].value,
							categoryLabel: recordType === 'income' ?
								this.incomeCategories[this.selectedCategory].label : this.expenseCategories[this
									.selectedCategory].label,
							amount: parseFloat(this.amount),
							date: this.selectedDate,
							remarks: this.remarks || ''
						};

						uni.setStorageSync('accountingRecords', accountingRecords);
						uni.showToast({
							title: '记录更新成功',
							icon: 'success'
						});

						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					} else {
						uni.showToast({
							title: '未找到记录',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('保存记录失败:', e);
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		position: relative;
	}

	/* 导航栏样式 */
	.navbar-left,
	.back-navigator,
	.back-content {
		display: flex;
		align-items: center;
	}

	.navbar-title {
		font-size: 16px;
		font-weight: 600;
		color: #1e88e5;
		margin-left: 8px;
	}

	/* 内容区样式 */
	.content-container {
		margin: 0 auto;
		padding: 16px;
		padding-bottom: 80px;
		box-sizing: border-box;
	}

	.form-card {
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		padding: 16px;
	}

	/* 表单样式 */
	.form-row {
		margin-bottom: 16px;
		width: 100%;
	}

	.form-field {
		display: flex;
		flex-direction: row;
		align-items: center;
		/* 整行垂直居中 */
		width: 100%;
	}

	/* 标签容器 - 核心样式 */
	.label-container {
		display: flex;
		align-items: center;
		/* 标签与星号垂直居中 */
		width: 110px;
		/* 固定宽度确保对齐 */
		flex-shrink: 0;
		padding-right: 12px;
		box-sizing: border-box;
	}

	/* 字段标签 - 两端对齐且垂直居中 */
	.field-label {
		font-size: 14px;
		color: #6b7280;
		flex: 1;
		/* 占满可用空间 */
		text-align: justify;
		/* 两端对齐 */
		text-align-last: justify;
		/* 最后一行两端对齐 */
		line-height: 1;
	}

	/* 解决短文本无法两端对齐问题 */
	.field-label::after {
		content: "";
		display: inline-block;
		width: 100%;
	}

	/* 必选星号 */
	.required-star {
		color: #f44336;
		margin-left: 4px;
		font-size: 16px;
		line-height: 1;
	}

	/* 输入区域样式 */
	.input-wrapper,
	.picker-field,
	.date-picker {
		flex-grow: 1;
		width: 100%;
	}

	.text-input,
	.picker-display {
		width: 100%;
		height: 40px;
		padding: 0 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	.text-input {
		padding-left: 12px;
		/* 调整左侧内边距 */
	}

	.picker-display {
		line-height: 40px;
		/* 文字垂直居中 */
	}

	/* 文本域样式 */
	.textarea-field {
		flex-grow: 1;
		min-height: 80px;
		padding: 8px 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		resize: vertical;
		box-sizing: border-box;
	}

	/* 文本域所在行调整 */
	.form-row:last-child .form-field {
		align-items: flex-start;
		padding-top: 4px;
	}

	/* 底部按钮 */
	.fixed-bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		padding: 12px 16px;
		box-sizing: border-box;
		display: flex;
		gap: 12px;
		max-width: 750rpx;
		margin: 0 auto;
	}

	.btn {
		flex: 1;
		height: 44px;
		line-height: 44px;
		text-align: center;
		border-radius: 8px;
		font-size: 15px;
		font-weight: 500;
	}

	.cancel-btn {
		background-color: #f3f4f6;
		color: #4b5563;
		text-decoration: none;
	}

	.save-btn {
		background-color: #1e88e5;
		color: #ffffff;
		border: none;
	}

	.cancel-btn:active {
		background-color: #e5e7eb;
	}

	.save-btn:active {
		background-color: #1976d2;
	}
</style>